from django.http import HttpResponse
from django.shortcuts import render
from rango.models import Category, Page
from rango.forms import CategoryForm


def index(request):

    TopFiveCats = Category.objects.order_by('-likes')[:5]
    
    pages = Page.objects.order_by('-views')[:5] 
    # Construct a dictionary to pass to the template engine as its context.
    # Note the key boldmessage is the same as {{ boldmessage }} in the template!
    context_dict = {'boldmessage': "Crunchy, creamy, cookies, candy, cupcake!",
                    'categories': TopFiveCats,
                    'pages': pages}

    # Return a rendered response to send to the client.
    # We make use of the shortcut function to make our lives easier.
    # Note that the first parameter is the template we wish to use.
    return render(request, 'rango/index.html', context=context_dict)

def about(request):
    return render(request, 'rango/about.html', context={'your_name': 'GerogeLiu'})



def show_category(request, category_slug_name):
    context_dict = {}
    try:
        category = Category.objects.get(slug=category_slug_name)
        pages = Page.objects.filter(category=category)
        context_dict['category'] = category
        context_dict['pages'] = pages
    except Category.DoesNotExist:
        context_dict['category'] = None
        context_dict['pages'] = None
    
    return render(request, 'rango/category.html', context_dict)

       

def index_add_category(request):
    TopFiveCats = Category.objects.order_by('-likes')[:5]
    pages = Page.objects.order_by('-views')[:5] 
    context_dict = {'boldmessage': "Crunchy, creamy, cookies, candy, cupcake!",
                    'categories': TopFiveCats,
                    'pages': pages}

    form = CategoryForm()
    if request.method == 'POST':
        form = CategoryForm(request.POST)
        if form.is_valid():
            form.save(commit=True)
            return index(request)
        else:
            print(form.errors)
    context_dict['form'] = form
    return render(request, 'rango/index_add_category.html', context_dict)
